<style lang='scss'>
#base-info {
  .convert-dialog > .el-dialog {
    width: 1700px;
  }

  .el-textarea.is-disabled .el-textarea__inner,
  .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }

  .form-table {
    .el-table__fixed-header-wrapper > table > thead > tr > th > .cell,
    .el-table__header-wrapper > table > thead > tr > th > .cell {
      padding: 10px 0;
      text-align: center;
      font-weight: bold;
    }
  }

  .el-table-column--selection > .cell {
    text-align: center;
  }
  .part {
    border: 1px solid #ccc;
    margin-bottom: 20px;
    background-color: #fff;
    .table-title {
      cursor: pointer;
      padding: 10px;
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
    }
  }
  .mt15 {
    margin-top: 15px;
  }
}
</style>
<template>
  <div id="base-info">
    <Box>
    <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyForm" :label-position="'' | LABEL_POSITION">
      <div v-if="modifyForm.editType">
        <el-row>
          <el-col :span="24">
            <!-- <el-form-item prop="content" class="mt15">
              <el-input
                type="textarea"
                :autosize="{ minRows: 20, maxRows: 30}"
                v-model="modifyForm.content"
                placeholder="请编辑content内容,content内容必须是标准的json格式,否则程序会报错!"
              ></el-input>
            </el-form-item> -->
            <MonacoEditor :jsonData.sync="modifyForm.content" ref="jsonData1"></MonacoEditor>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <div v-for="(value,key,index) in modifyForm" :key="index">
          <div class="part" v-if=" Object.prototype.toString.call(modifyForm[key]) == '[object Array]' ">
            <div class="table-title">
              <el-button style="margin-left:10px;" type="primary" size="small" @click="onFold(index)">{{fold[index] == true ? '收起':'展开'}}</el-button>
            </div>
            <div v-show="fold[index]!=undefined ? fold[index] : true">
              <el-table
                v-loading="regionLoading"
                element-loading-spinner="el-icon-loading"
                :data="modifyForm[key]"
                border
                class="form-table"
                max-height="400"
                @selection-change="handleSelectionChange($event,key)"
              >
                <el-table-column v-if="type !='view'" type="selection" width="55" class="tc"></el-table-column>
                <el-table-column label="描述" min-width="200">
                  <template slot-scope="scope">
                    <el-form-item :prop=" key+'.' + scope.$index + '.desc' " :rules="modifyFormRules.desc" class="mt15">
                      <el-input
                        type="textarea"
                        :readonly="type == 'view'"
                        :autosize="{ minRows: 1, maxRows: 1}"
                        v-model="scope.row.desc"
                        placeholder="请输入描述"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="code" min-width="200">
                  <template slot-scope="scope">
                    <el-form-item :prop=" key+'.'  + scope.$index + '.code' " :rules="modifyFormRules.code" class="mt15">
                      <el-input
                        type="textarea"
                        :readonly="type == 'view'"
                        :autosize="{ minRows: 1, maxRows: 1}"
                        v-model="scope.row.code"
                        placeholder="请输入code"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="值" min-width="200">
                  <template slot-scope="scope">
                    <el-form-item :prop=" key+'.' +scope.$index + '.value' " :rules="modifyFormRules.value" class="mt15">
                      <el-input
                        type="textarea"
                        :readonly="type == 'view'"
                        :autosize="{ minRows: 1, maxRows: 1}"
                        v-model="scope.row.value"
                        placeholder="请输入value"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>

              <el-row v-if="type != 'view'">
                <el-col :span="24" class="tc mt20 mb20">
                  <el-button type="primary" @click="addItem(key)">新增Item</el-button>
                  <el-button type="warning" :disabled="selection.length == 1" @click="delItem(key)">删除Item</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <el-row v-if=" modifyForm.editType">
      <el-col :span="24" class="tc">
        <el-button type="primary" @click="onSubmitForm">新增</el-button>
        <el-button type="danger" @click="modifyForm.content=`${initStr}`;">重置</el-button>
      </el-col>
    </el-row>

    <el-row v-else>
      <el-col :span="24" class="tc">
        <el-button type="primary" @click="onSubmitForm">{{type == 'view' ? '编辑' : '保存'}}</el-button>
        <el-button type="danger" v-if=" type != 'view' " @click="onDelRecord">删除</el-button>
      </el-col>
    </el-row>
    </Box>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import SearchContainer from "src/components/common/SearchContainer";
import storage from "src/utils/storage";
import { sendReq, tableExportExcel, isJSON,GetQueryString } from "src/utils/tools";
import MonacoEditor from "src/components/common/MonacoEditor"

export default {
  data() {
    const pagePermissionsMenu = storage.get("pagePermissionsMenu")
      ? storage.get("pagePermissionsMenu")
      : {};

    const inputWarning = (msg) => {

      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change",
        }
      ];
    };
    let checkEmpty = (obj) => {

      return (rule, value, callback) => {


        if (value != undefined) {
          return callback(new Error(obj.msg));
        } else {
          callback();
        }
      };
    };

    let checkJSON = (obj) => {

      return (rule, value, callback) => {

        if (value != 0 && !value) {
          return callback(new Error(obj.msg));
        }


        if (!isJSON(value, true)) {
          callback(new Error('数据不是标准的json格式'));
        } else {
          callback();

        }
      }
    };

    let validateContent = (obj) => ([{ required: true, validator: checkJSON(obj), trigger: 'blur' }]);

    let validateEmpty = (obj) => ([{ required: true, validator: checkEmpty(obj), trigger: 'blur' }]);
    let initStr = '{ \n\n}';
    return {
      fold: [],
      type: 'view',
      initStr: initStr,
      modifyForm: {
        content: initStr,
        editType: 'add',
      },
      args: {},
      modifyFormRules: {
        desc: inputWarning('请输入描述'),
        code: inputWarning('请输入code'),
        value: inputWarning('请输入value'),
        content: validateContent({ msg: '内容不能为空' }),
      },
      selection: [],
    };
  },
  components: {
    SearchContainer,MonacoEditor
  },
  computed: {
    ...mapGetters(["pagination", "regionLoading"])
  },
  watch: {},
  created() {

  },
  mounted() {


    // sendReq({
    //   url: '/config/deleteNode',
    //   params: { path: '/za-pre-product-config/testB' },
    //   note: true,
    //   cb: (data) => {
    //     // this.onSearch();
    //   }
    // })

    this.onSearch();



  },
  methods: {
    ...mapActions([""]),
    onSearch() {
      sendReq({
        url: '/config/getCommonConfig',
        params: { productCode: this.$route.params.productCode, type: 'product' },
        cb: (data) => {

          if (!data) return;
          let { zkConfigTypeEnum, name } = data;
          this.args = { zkConfigTypeEnum, name };


          // 有内容展示编辑
          if (data.content) {
            delete data.content.productCode;
            this.modifyForm = data.content;
            this.path = data.path;
            delete this.modifyForm.editType;
            this.boolToStr({
              src: this.modifyForm,
              to: 'str',
              cb: () => { }
            })
          }//没内容展示新增
          else {
            this.modifyForm.editType = 'add';
            this.modifyForm.content = this.initStr;
          }
        }
      })
    },
    boolToStr(obj) {

      let keyArray = Object.keys(obj.src);
      keyArray.some((key, index) => {
        index == 0 ? this.fold.push(true) : this.fold.push(false);

        if (Object.prototype.toString.call(obj.src[key]) != '[object Array]') { return true; }
        // 将Boolean值转换成字符串
        obj.src[key].forEach((item) => {

          if (obj.to == 'str') {
            if (item.value === true || item.value === false) {
              item.value = item.value + '';
            } else if (isJSON(item.value, true)) {
              item.value = JSON.stringify(item.value);
            }
          } else if (obj.to == 'bool') {
            if(item.value == "0"){
              return
            }
            if (item.value == true) {
              item.value = true;
            } else if (item.value == false) {
              item.value = false;
            } else if (isJSON(item.value, true)) {
              item.value = JSON.parse(item.value);
            }
          }
        });
      });


      return obj.src;
    },
    onFold(index) {
      this.fold.splice(index, 1, !this.fold[index]);
      // console.log(this.fold);
    },
    handleSelectionChange(selection, key) {
      this.selection[key] = selection;
      // console.log(selection, key);
    },
    addItem(key) {
      console.log(key);
      this.modifyForm[key].push({
        code: null,
        desc: null,
        value: null,
      })
    },
    delItem(key) {

      this.$confirm("确定要删除这条记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {

        this.selection[key].forEach((item, index) => {
          for (var i = 0, len = this.modifyForm[key].length; i < len; i++) {
            if (this.modifyForm[key][i].code == item.code) {
              this.modifyForm[key].splice(i, 1);
              break;
            }
          }
        })
      });
    },
    //新增&&编辑保存
    onSubmitForm() {

      if (this.type == 'view' && !this.modifyForm.editType) {
        this.type = 'edit';
        return;
      }

      let params = {
        type: this.type,
      };

      this.$refs.modifyForm.validate(valid => {
        if (valid) {

          this.$confirm("确定要提交数据吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            let url, content;
            if (this.modifyForm.editType) {
              if(!isJSON(this.$refs.jsonData1.getJsonData())){
                return
              }
              content = JSON.parse(this.$refs.jsonData1.getJsonData())
              //content = eval('(' + this.modifyForm.content + ')');
              url = '/config/addNode';
              delete content.editType;
            } else {
              console.log(this.modifyForm);

              content = JSON.parse(JSON.stringify(this.modifyForm));
              console.log(content)
              
              delete content.content;
              // 将字符型bool值转换成bool值
              this.boolToStr({
                src: content,
                to: 'bool',
              })
              content.productCode = this.$route.params.productCode;
              url = '/config/updateNode';
            }
            
            sendReq({
              url: url,
              params: {
                productCode: this.$route.params.productCode,
                content: content,
                name: this.args.name,
                zkConfigTypeEnum: this.args.zkConfigTypeEnum
              },
              note: true,
              cb: (data) => {
                this.onSearch();
              }
            })
          })

        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      });
    },
    // 删除
    onDelRecord(params) {

      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {

        sendReq({
          url: '/config/deleteNode',
          params: { path: this.path },
          note: true,
          cb: (data) => {
            this.onSearch();
          }
        })

      })

    },
  }
};
</script>
